package com.example.octopus.controller;

import com.alibaba.fastjson2.JSON;
import com.example.octopus.entity.Detail;
import com.example.octopus.entity.Keyword;
import com.example.octopus.entity.Product;
import com.example.octopus.entity.returnMessage.DeleteReturnMessage;
import com.example.octopus.entity.returnMessage.InsertReturnMessage;
import com.example.octopus.entity.returnMessage.SelectReturnMessage;
import com.example.octopus.entity.returnMessage.UpdateReturnMessage;
import com.example.octopus.entity.returnMessage.ProductSelectAllReturnMessage;
import com.example.octopus.entity.returnMessage.ProductSelectReturnMessage;
import com.example.octopus.service.ProductService;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.google.gson.Gson;
import lombok.Data;
import lombok.NonNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.example.octopus.entity.returnMessage.ProductInsertOrDeleteReturnMessage;

import java.util.*;
@RestController
@RequestMapping("api/detail/detail")
public class ProductController {
    @Autowired
    ProductService productService;
    @Autowired
    Gson gson;
    private static final String TrueNumber ="0";
    private static final int TureReturnCOde=200;
    private static final int ErrReturnCode =500;
    //等待yml注入
    String env="cloud1-6gma1k2s0ff0ac6b";
    @PostMapping
    public ProductInsertOrDeleteReturnMessage createProduct(@RequestBody Detail detail){
        // 生成一个随机UUID字符串并去除连字符作为数据库表主键_id
        String randomString = UUID.randomUUID().toString().replaceAll("-", "");
        if (randomString.length() != 32) {
            System.out.println("生成字符串长度不正确，应该为32位。");
        } else {
            // 输出生成的32位随机字符串
            System.out.println(randomString);
        }
        Product product=ParseToProduct(detail);
        product.set_id(randomString);
        //检测是否有重复id，有就拒绝插入
        HashMap<String,Object> condition = new HashMap<>();
        condition.put("_id",product.get_id());
        System.out.println(condition);
        System.out.println(product);
        if(productService.select(env,condition).getData().isEmpty()){
            ArrayList<Product> products=new ArrayList<>();
            products.add(product);
            //数据库插入返回
            InsertReturnMessage insertReturnMessage=productService.insert(env,products);
            if(insertReturnMessage.getErrcode().equals(TrueNumber)){
                return new ProductInsertOrDeleteReturnMessage(TureReturnCOde, insertReturnMessage.getErrmsg());
            }else{
                return new ProductInsertOrDeleteReturnMessage(ErrReturnCode, insertReturnMessage.getErrmsg());
            }
        }
        System.out.println(productService.select(env,condition).getData());
        return new ProductInsertOrDeleteReturnMessage(ErrReturnCode, "数据库错误");
    }
    @GetMapping("/pages/{page}")
    public  ProductSelectAllReturnMessage getAllProducts(@PathVariable int page) {
        SelectReturnMessage selectReturnMessage=productService.selectAll(env,page);
        if(selectReturnMessage.getErrcode().equals(TrueNumber)){
            List<Detail> details=new ArrayList<>();
            for(String s: selectReturnMessage.getData()){
                Detail detail= ParseToDetail(JSON.parseObject(s, Product.class));
                details.add(detail);
            }
            return new ProductSelectAllReturnMessage(selectReturnMessage.getErrmsg(), details, TureReturnCOde);
        }else {
            return new ProductSelectAllReturnMessage(selectReturnMessage.getErrmsg(), null, ErrReturnCode);
        }
    }
    @GetMapping("/{id}/pages/{page}")
    public ProductSelectReturnMessage getProductById(@PathVariable String id,@PathVariable int page) {
        Map<String,Object> conditions=new HashMap<>();
        conditions.put("_id",id);
        SelectReturnMessage selectReturnMessage=productService.select(env,conditions,page);
        if(selectReturnMessage.getErrcode().equals(TrueNumber)){
            if(selectReturnMessage.getData().size()==1){
                for(String s: selectReturnMessage.getData()){
                    Detail detail= ParseToDetail(JSON.parseObject(s,Product.class));
                    if(detail.getNote()==null){
                        detail.setNote("无详细描述");
                    }
                    return new ProductSelectReturnMessage(TureReturnCOde, detail, selectReturnMessage.getErrmsg());
                }
            }else{
                return new ProductSelectReturnMessage(ErrReturnCode, null, "不存在");
            }
        }
        return new ProductSelectReturnMessage(ErrReturnCode, null, selectReturnMessage.getErrmsg());
    }

    @PutMapping("/{id}")
    public ProductInsertOrDeleteReturnMessage updateProduct(@PathVariable String id, @RequestBody Detail detail) {
        UpdateReturnMessage updateReturnMessage= productService.update(env,id,ParseToProduct(detail));
        if(updateReturnMessage.getErrcode().equals(TrueNumber)){
            return new ProductInsertOrDeleteReturnMessage(TureReturnCOde, updateReturnMessage.getErrmsg());
        }else {
            return new ProductInsertOrDeleteReturnMessage(ErrReturnCode, updateReturnMessage.getErrmsg());
        }
    }
    @DeleteMapping("/{id}")
    public ProductInsertOrDeleteReturnMessage deleteProduct(@PathVariable String id){
        Map<String,Object> conditions=new HashMap<>();
        conditions.put("_id",id);
        DeleteReturnMessage deleteReturnMessage=productService.delete(env,conditions);
        if(deleteReturnMessage.getErrcode().equals(TrueNumber)){
            return new ProductInsertOrDeleteReturnMessage(TureReturnCOde, deleteReturnMessage.getErrmsg());
        }else {
            return new ProductInsertOrDeleteReturnMessage(ErrReturnCode, deleteReturnMessage.getErrmsg());
        }
    }

    @PostMapping(value = "/get/getByTitle/pages/{page}")
    public  ProductSelectAllReturnMessage selectByTitle(@RequestBody Keyword _keyword,@PathVariable int page){
        String keyword=_keyword.getKeyword();
        System.out.println(keyword);
        if(_keyword==null||keyword==null||keyword.isEmpty()){
            List<Detail> details=new ArrayList<>();
            SelectReturnMessage selectReturnMessage=productService.selectAll(env,page);
            for(String s: selectReturnMessage.getData()){
                Detail detail= ParseToDetail(JSON.parseObject(s, Product.class));
                details.add(detail);
            }
            return new ProductSelectAllReturnMessage("ok",details,TureReturnCOde);
        }
        System.out.println(keyword);
        List<Product> products=productService.selectByTitle(env,keyword,page);
        if(products==null){
            return new ProductSelectAllReturnMessage("无对应商品", null,ErrReturnCode);
        }
        List<Detail> details=new ArrayList<>();
        for(Product p:products){
            Detail detail=ParseToDetail(p);
            details.add(detail);
        }
        return new ProductSelectAllReturnMessage("ok",details,TureReturnCOde);
    }

    @GetMapping("/types/{type}/pages/{page}")
    public  ProductSelectAllReturnMessage selectByTitle(@PathVariable String type, @PathVariable int page){
        Map<String,Object> conditions=new HashMap<>();
        conditions.put("type",type);
        SelectReturnMessage selectReturnMessage=productService.select(env,conditions,page);
        if(selectReturnMessage.getErrcode().equals(TrueNumber)){
            List<Detail> details=new ArrayList<>();
            for(String s:selectReturnMessage.getData()){
                Detail detail=ParseToDetail(JSON.parseObject(s,Product.class));
                details.add(detail);
            }
            return new ProductSelectAllReturnMessage(selectReturnMessage.getErrmsg(),details,TureReturnCOde);
        }else {
            return new ProductSelectAllReturnMessage(selectReturnMessage.getErrmsg(),null,ErrReturnCode);
        }
    }
    @GetMapping("/openid/{openid}/pages/{page}")
    public ProductSelectAllReturnMessage selectByUserId(@PathVariable String openid,@PathVariable int page){
        Map<String,Object> conditions=new HashMap<>();
        conditions.put("_openid",openid);
        SelectReturnMessage selectReturnMessage=productService.select(env,conditions,page);
        if(selectReturnMessage.getErrcode().equals(TrueNumber)){
            List<Detail> details=new ArrayList<>();
            for(String s:selectReturnMessage.getData()){
                Detail detail=ParseToDetail(JSON.parseObject(s,Product.class));
                details.add(detail);
            }
            return new ProductSelectAllReturnMessage(selectReturnMessage.getErrmsg(),details,TureReturnCOde);
        }else {
            return new ProductSelectAllReturnMessage(selectReturnMessage.getErrmsg(),null,ErrReturnCode);
        }
    }


    private static Product ParseToProduct(Detail detail){
        Product product=new Product();
        product.set_id(detail.getId());
        product.setAddress(detail.getAddress());
        product.setPrice(detail.getPrice());
        product.setType(detail.getType());
        product.setContact(detail.getContact());
        product.setTitle(detail.getTitle());
        product.setUserId(detail.get_openid());
        product.setImg(detail.getImg());
        product.setNote(detail.getNote());
        product.setState(detail.getState());
        return product;
    }

    private static Detail ParseToDetail(Product product){
        Detail detail=new Detail();
        detail.setId(product.get_id());
        detail.setAddress(product.getAddress());
        detail.setPrice(product.getPrice());
        detail.setType(product.getType());
        detail.setContact(product.getContact());
        detail.setTitle(product.getTitle());
        detail.set_openid(product.getUserId());
        detail.setImg(product.getImg());
        detail.setNote(product.getNote());
        detail.setState(product.getState());
        return detail;
    }
}

